3.0 Something More About JavaScript

  1. Prerequisites
    • Roles of HTML5, CSS3, and JavaScript

  2. Motivations
    • You have used JavaScript for simple examples.
    • It is about the time to learn more topics in JavaScript.
    • For example, functions, objects, arrays, and the runtime environment.

  3. JavaScript Tutorial
    • An example: menu for TruQA
        • Sign In
        • Join
        • Forgot Password

    • Why do we need a programming lanaguage in a web app?
      • User interaction: events, inputs, outputs
      • Exchange data with server side scripts
      • ...

    • Basics
        <!DOCTYPE html>
        <html>
            <head>
                <style>
                </style>
                <script>
                </script>
            </head>
            <body>
                <script>
                </script>
            </body>
            <script>
            </script>
        </html>
        <script>
        </script>
        
      • Anywhere within <script> and </script>; Multiple scripts share the same memory space.
      • JavaScript is a loosely typed programming language.
      • Code block: { ... }
      • Declaration of variables and constants: var, let, const; Let's not use var variables except when you need them for testing. Let's use let. (Note that you cannot redeclare the same let variables.)
        {
            const PI = 3.14159;
            let radius = prompt("Enter a number: ");  // or window.prompt(...)
            let circumference;
            circumference = 2 * PI * radius;
            alert(circumference);  // or window.alert(...)
        }
        
      • Trial 0.01: Let's write the code that reads diameter, computes area, and prints the result using alert().


      • Operators:
        • Arithmetic operators: ..., %, **
        • Comparision operators: ...
        • Assignment operators: ...
        • Function invocation: ...
        • String concatenation: +
        •     let name = prompt("Enter a name: ");
              let message = "Welcome " + name + "!";
              alert(message);
          
        • Object membership: .
              document.getElementById('modal-login').style.display = 'block';
          
      • Selection structures - if, if-else, if-else if-else, switch
      • Loop structures - for, while, do-while
      • If you think you don't remember much about the Basics, you may visit JavaScript Tutorial and study them.
      • Run-time environment: Web browser
        • Window is represented by window object.
            For examples,
          • window.promt() or just promt()
          • window.alert() or just alert()
          • window.document or just document
        • Document Object Model (DOM) is a tree like data struncture that includes all the HTML elements. DOM is representd by the object document.
            For examples,
          • document.getElementById("target").style.backgroundColor = "Cyan";
          • alert(document.getElementById("target").innerHTML);
          • <button id='target'>Click me!</button>
            <div id='display'>Message here</div>
            <script>
                document.getElementById("target").addEventListener("click", function() {  // "click" event listener
                    document.getElementById("display").innerHTML = "Interesting!";
                });
            </script>
            
          • Trial 0.02: Try the above example.



    • Read all in JavaScript Functions.
      • For what do we use functions?
        Modular programming
      • Function used as a variable value - How are 'toCelsius()' and 'toCelsius' different in the 4th example?
      • Function object in the 4th example? This is very interesting.
      • Can you assign a function to a variable? If so, how to use the function variable?
      • Trial 0.1: Let's write a function to check if a given number is a prime number. You need to include the code to test the function as well. Note that a prime number is a natural number and is divisible only by 1 and itself. You may use % operator.


      • Trial 0.2: Let's write a function to compute Fibonacci number, and test the function with a number read from the user. (Don't test the function with any number larger than 40.)
        Fibonacci numbers: 0, 1, 1, 2, 3, 5, 8, ...; F(0)=0, F(1)=1, F(n)=F(n-2)+F(n-1) for n >= 2



    • Read all in JavaScript Objects.
      • What do real life objects contain?
      • What do JavaScript objects contain?
      • How to define an object?
      • What are object properties?
      • What is a method?
      • Give two different styles to access object properties.
      • Give two different styles to access object methods.
      • How to add methods into an object?
      • Trial 0.3: Let's write a function that have two parameters, a name and an id, and it creates/returns a Student object that includes the name the id. Test the function. The Student object includes two properties - name and id, and two methods - getName() and setName().



    • Read all in JavaScript Scope.
      • What is the function of the var keyword and when to use it (or omit it)?
        • In the global scope, there's no difference.
        • In a local scope, 'var' will create a local variable, and no 'var' will look up the scope chain until it finds the variable or hits the global scope (at which point it will create it).
        • Here is an example.
          // These are both globals.
          let foo = 1;
          var bar = 2;
          
          function test() {
              let foo = 1; // Local
              bar = 1;     // Global
          
              // Execute an anonymous function. Isn't it interesting?
              (function() {
                  let wibble = 1; // Local
                  foo = 3; // Inherits from scope above (creating a closure)
                  moo = 3; // Global??? You should be careful with this.
              })();
              
              alert(foo);
              alert(bar);
              alert(moo);
              alert(wibble);
          }
          
          test();
          
      • Study closely the code of the last example, window.carName, in the above link.
      • What object is used for the global scope? What if a property of the object is overwritten?
      • Trial 1: Let's try the above example. Can you see five alert windows? If not, why not?



    • Read all in JavaScript Arrays.
      • How to create an array?
      • List the two different styles of array creation.
      • Can you put different objects to one array?
      • How are arrays different from objects?
      • List some built-in array properties and methods.
      • How to add a new element to an array?
      • Are arrays with named indexes, i.e., associative arrays, supported?
      • Here is one thing that you really need to be careful. If you use a named index, when accessing an array, JavaScript will redefine the array to a standard object, and all array methods and properties will produce undefined or incorrect results. Study closely the 11th example.
      • But try the 11th example after you add person[2] = 'Dave';. What do you see?
      • What is the difference between arrays and objects?
      • The reason not to use 'new Array(...)'. Study closely the 13th example.
      • How do you know if a variable is an array or object?
      • Comparison of linear arrays and objects:
        Linear arraysObjects (associative arrays)
        const x = [];const o = {};
        x[2] = 'Wow!';o.today = 'Friday'; o['today'] = 'Saturday'; let p = "today"; o[p] = "Monday";
        delete x[1];delete o.another;
        for(let i = 0; i < x.length; i++)
           alert(x[i]);
        for (let p in o)
           alert(p + ":" + o[p]);

    • Read all in JavaScript For In Loop.
      • Trial 1.1: Let's write a function to display the content of an objects, and test the function. You need to use for-in loop for objects.


      • Trial 1.2: Let's write a function to display the content of a linear array of objects, and test the function. You need to use for-in loop for objects.



    • Here are some very useful methods. JavaScript Array Methods (linear arrays).

  4. New features in the latest revisions (We won't use these new features except let and const in this course.)